<template>
  <div>
    <div
      style="background: #fff; padding: 20px;min-height: 89vh;margin-top: 80px;overflow: hidden;overflow-y: scroll;"
    >
      <div style="width: 80%;margin-left: 10%;">
        <h3 class="flex-between header">
          <div class="fun-name">{{ hotelDetail.name }}</div>
          <div class="flex-center">
            <img
              @click="doLikeFun"
              :title="!liked ? '收藏' : '取消收藏'"
              :src="!liked ? unlikeImg : likeImg"
              alt=""
            />
            <div class="dp-btn cp mr10" @click="buyTicket">预定</div>
            <div class="dp-btn cp" @click="toComment">我要点评</div>
          </div>
        </h3>
        <el-rate
            v-model="rate"
            disabled
            show-score
            text-color="#ff9900"
            :score-template="rate + ''">
          </el-rate>
        <el-carousel height="500px" style="margin-top: 10px;">
          <el-carousel-item v-for="item in hotelDetail.pics" :key="item.img">
            <div style="position: relative;">
              <img
                ref="img"
                style="width: 100%;height: 500px;"
                :src="item"
                alt=""
              />
            </div>
          </el-carousel-item>
        </el-carousel>

        <div class="desc">{{ hotelDetail.funDesc }}</div>
        <div class="comments">
          <el-checkbox @change="filterComment" v-model="filter.img">只看有图片的评价</el-checkbox>
          <el-checkbox @change="filterComment" v-model="filter.low">只看低分</el-checkbox>
          <div
            class="each-comment"
            v-for="(c, i) in commentsFilter"
            :key="i"
          >
            <img class="avator" v-if="c.userInfo[0].avator" :src="c.userInfo[0].avator" alt="">
            <div class="avator avator2" v-if="!c.userInfo[0].avator">
              <i style="margin: auto;" class="el-icon-user"></i>
            </div>

            <div class="comment-block" v-if="c.comment">
              <div class="mb10">{{c.userInfo[0].username}}</div>
              <div class="flex-center mb10"><div>居住体验：</div><el-rate disabled score-template="{c.comment.ywty}" v-model="c.comment.ywty"></el-rate></div>
              <div class="flex-center mb30"><div>酒店服务：</div><el-rate disabled score-template="{c.comment.mjfw}" v-model="c.comment.mjfw"></el-rate></div>
              <div class="mb10">{{c.comment.content}}</div>
              <div class="picsss">
                <img v-for="(img,index) in JSON.parse(c.comment.pics)" :src="img" alt="" :key="index">
              </div>
            </div>

            <el-button type="danger" size="mini" @click="doDelete(c)" class="delete" v-if="c.userInfo[0]._id === userInfo._id">删除评论</el-button>
            <div class="zan">
              <img v-if="c.thumbs.map(v => v.userId).includes(userInfo._id)" @click="zan(false, c, i)" src="../assets/images/zan.svg" alt="">
              <img v-if="!c.thumbs.map(v => v.userId).includes(userInfo._id)" @click="zan(true, c, i)" src="../assets/images/unzan.svg" alt="">
              <div>({{c.thumbs.length}})</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      title="预定"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <div class="flex-center">
        <div class="mr10">选择时间</div>
        <el-date-picker
          v-model="date"
          class="mr10"
          size="mini"
          align="right"
          type="date"
          placeholder="选择日期"
          :picker-options="pickerOptions"
        >
        </el-date-picker>
      </div>
      <div class="row" v-for="item in roomInfo">
        <div style="width: 80px;text-align: right;">{{ item.type }}</div>
        <div>价格：<el-input-number v-model="item.price" label="价格"></el-input-number></div>
        <div>数量：<el-input-number v-model="item.buyCnt" label="数量："></el-input-number></div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="doBuy">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="添加评论"
      :visible.sync="commentVisible"
      width="50%"
      :before-close="handleClose2"
    >
      <div>
        <el-divider content-position="left">评分</el-divider>
        <div class="flex-center mb10">
          <div>居住体验：</div>
          <el-rate v-model="comment.ywty"></el-rate>
        </div>
        <div class="flex-center mb10">
          <div>酒店服务：</div>
          <el-rate v-model="comment.mjfw"></el-rate>
        </div>
        <el-divider content-position="left">评价内容</el-divider>
        <div>
          <div class="mb10">评价内容：</div>
          <el-input
            type="textarea"
            :autosize="{ minRows: 5, maxRows: 10}"
            placeholder="请输入内容"
            v-model="comment.content">
          </el-input>
        </div>
        <el-divider content-position="left">上传图片</el-divider>
        <div>
          <div v-if="comment.pics" class="img-blocks">
            <div
              v-for="(img, index) in comment.pics"
              :key="index"
              style="position: relative"
            >
              <img :src="img" style="width: 80px" />
              <i @click="deleteImg(index)" class="el-icon-circle-close"></i>
            </div>
          </div>
          <el-upload
            class="avatar-uploader"
            :action="'/upload'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="commentVisible = false">取 消</el-button>
        <el-button type="primary" @click="addComment">发表</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import moment from "moment";
import {
  getHotelById,
  getUserInfo,
} from "../service";
import { addLike, addComment, getComment, addThumb, deleteThumb, deleteComment, deleteLike, addTicket } from "../service";
export default {
  data() {
    return {
      rate: 0,
      userInfo: {},
      hotelDetail: {},
      input: "",
      liked: false, // 是否已经收藏
      commentVisible: false,
      dialogVisible: false,
      date: "",
      count: 0,
      commentVisible: false,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 1000 * 86400;
        },
      },
      comment: {
        ywty: 0,
        mjfw: 0,
        content: '',
        pics: []
      },
      filter: {
        img: false,
        low: false
      },
      roomInfo: [],
      comments: [],
      commentsFilter: [],
      unlikeImg: require('../assets/images/未收藏.svg'),
      likeImg: require('../assets/images/收藏.svg'),
    };
  },
  created() {
    let ls = localStorage.getItem("meiyaWebInfo");
    if (ls) {
      this.userInfo = JSON.parse(ls);
      getUserInfo(this.userInfo._id).then((res) => {
        this.userInfo = {
          ...res.data,
        };
      });
    }
    let hotelId;
    if (this.$route.params.id) {
      hotelId = this.$route.params.id;
    } else if (localStorage.getItem("meiyaFunDetail")) {
      hotelId = JSON.parse(localStorage.getItem("meiyaFunDetail")).id;
    } else {
      this.$router.push("/list");
    }
    console.log(hotelId)
    this.hotelId = hotelId;
    this.getFunDetail();
    this.getFunComment();
  },
  methods: {
    refreshRate() {
      console.log(this.comments)
      this.rate = 0;
      let sum = 0;
      let score = 0
      for (let c of this.comments) {
        sum++
        score += (c.comment.mjfw + c.comment.ywty) / 2
      }
      if (sum) {
        this.rate = Number((score / sum).toFixed(1))
      }
    },
    getFunComment() {
      getComment({
        hotelId: this.hotelId,
        type: 'hotel'
      }).then(res => {
        this.comments = res.data.sort((a, b) => {
          return b.thumbs.length - a.thumbs.length
        })
        // 需要对评论进行排序，赞多的排上面
        this.filterComment()
        this.refreshRate()
      })
    },
    getFunDetail() {
      getHotelById(this.hotelId).then((res) => {
        console.log(res)
        let likes = res.data.likes;
        res.data = {
          ...res.data.hotelInfo,
          tickets: res.data.tickets
        }
        res.data.roomInfo = JSON.parse(res.data.roomInfo)
        res.data.pics = res.data.pics.split(",");
        this.hotelDetail = res.data;
        console.log(this.hotelDetail)
        // 判断是否关注
        if (likes.map(v => v.userId).includes(this.userInfo._id)) {
          this.liked = true;
        } else {
          this.liked = false;
        }
      });
    },
    addComment() {
      if (!this.userInfo.username) {
        this.$notify({
          title: "提示",
          message: "请先登录",
          duration: 0,
        });
        return;
      }
      if (!this.comment.content) {
        this.$message.error('请填写评论')
        return
      }
      this.filterComment()
      addComment({
        userId: this.userInfo._id,
        hotelId: this.hotelDetail._id,
        content: this.comment.content,
        pics: JSON.stringify(this.comment.pics),
        ywty: Number(this.comment.ywty),
        mjfw: Number(this.comment.mjfw),
        type: 'hotel'
      }).then(res => {
        this.$message.success("评论成功");
        this.commentVisible = false
        this.getFunComment();
      })
    },
    // 收藏或取消收藏
    doLikeFun() {
      if (!this.userInfo.username) {
        this.$notify({
          title: "提示",
          message: "请先登录",
          duration: 0,
        });
        return;
      }
      if (this.liked) {
        // 取消收藏
        // 删除likes
        deleteLike({
          hotelId: this.hotelDetail._id,
          userId: this.userInfo._id
        }).then(res => {
          if (res.code === 200) {
            this.$message.info('取消收藏')
            this.getFunDetail()
          }
        })
      } else {
        addLike({
          hotelId: this.hotelDetail._id,
          userId: this.userInfo._id,
          type: 'hotel'
        }).then(res => {
          if (res.code === 200) {
            this.$message.success('收藏成功')
            this.getFunDetail()
          }
        })
      }
    },
    toComment() {
      // 买票了才能评论
      if (this.hotelDetail.tickets.map(v => v.userId).includes(this.userInfo._id)) {
        this.commentVisible = true
        this.$nextTick(() => {
          this.comment = {
            ywty: 0,
            mjfw: 0,
            content: '',
            pics: []
          }
        })
      } else {
        this.$message.error('您未购买过该酒店，无法进行点评。')
      }
    },
    handleClose() {
      this.dialogVisible = false;
    },
    handleClose2() {
      this.commentVisible = false;
    },
    buyTicket() {
      this.roomInfo = JSON.parse(JSON.stringify(this.hotelDetail.roomInfo.map(v => {
        return {
          type: v.type,
          price: v.price,
          buyCnt: 0
        }
      })))
      if (!this.userInfo.username) {
        this.$notify({
          title: "提示",
          message: "请先登录",
          duration: 0,
        });
        return;
      }
      this.date = "";
      this.count = 1;
      this.dialogVisible = true;
    },
    doBuy() {
      if (!this.date) {
        this.$message.error("请选择日期");
        return;
      }
      if (!this.roomInfo.filter(v => v.buyCnt)) {
        this.$message.error("请选择房型");
        return;
      }
      const room = this.roomInfo.filter(v => v.buyCnt)
      let roomText = ''
      for (let item of room) {
        roomText += `${item.type}: ${item.buyCnt}间`
      }
      console.log(roomText)
      let text = `您将预定${moment(this.date).format('YYYY-MM-DD')} ${roomText}`
      // 确认
      this.$confirm(text, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let tickets = {
          userId: JSON.parse(localStorage.getItem("meiyaWebInfo"))._id,
          date: moment(this.date).format("YYYY-MM-DD"),
          count: this.count,
          buyTime: moment().format("YYYY-MM-DD HH:mm:ss"),
          hotelId: this.hotelDetail._id,
          hotelName: this.hotelDetail.name,
          pic: this.hotelDetail.pics[0],
          roomInfo: JSON.stringify(this.roomInfo),
          type: 'hotel'
        };
        addTicket(tickets).then(res => {
          if (res.code === 200) {
            this.$message.success('购买成功')
            this.getFunDetail();
            this.dialogVisible = false;
          }
        }) 
      })
    },
    deleteImg(index) {
      this.comment.pics.splice(index, 1);
    },
    handleAvatarSuccess(info) {
      this.comment.pics.push(info.url);
    },
    filterComment() {
      this.commentsFilter = JSON.parse(JSON.stringify(this.comments))
      if (this.filter.img) {
        this.commentsFilter = this.commentsFilter.filter(v => v.comment.pics !== '[]')
      }
      if (this.filter.low) {
        this.commentsFilter = this.commentsFilter.filter(v => (v.comment.mjfw < 2 || v.comment.ywty < 2))
      }
    },
    doDelete(c) {
      console.log(c)
      deleteComment(c.comment._id).then(res => {
        console.log(res)
        if (res.code === 200) {
          this.$message.success('删除成功')
          this.getFunComment();
        }
      })
    },
    zan(key, comment) {
      if (!this.userInfo.username) {
        this.$notify({
          title: "提示",
          message: "请先登录",
          duration: 0,
        });
        return;
      }
      console.log(comment)
      if (key) {
        // 点赞
        addThumb({
          commentId: comment.comment._id,
          userId: this.userInfo._id
        }).then(res => {
          if (res.code === 200) {
            this.$message.success('点赞成功')
            this.getFunComment()
          }
        })
      } else {
        deleteThumb({
          commentId: comment.comment._id,
          userId: this.userInfo._id
        }).then(res => {
          if (res.code === 200) {
            this.$message.success('取消点赞')
            this.getFunComment()
          }
        })
      }
    }
  },
};
</script>

<style lang="scss" scoped>
h4 {
  text-align: center;
  font-weight: bold;
}

.name {
  font-size: 20px;
  font-weight: bold;
  line-height: 40px;
}
.desc {
  margin-top: 20px;
  overflow: hidden;
  color: #666;
  text-indent:24px;
  text-overflow: ellipsis;
  display: -webkit-box;
  /* autoprefixer: off */
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 8;
  word-break: break-all;
  line-height: 24px;
  font-size: 16px;
  border-bottom: 1px solid #efd4d4;
  padding-bottom: 30px;
}

.flex-between {
  display: flex;
  justify-content: space-between;
}
.flex-center {
  display: flex;
  align-items: center;
}

.cp {
  cursor: pointer;
}

.comments {
  display: flex;
  flex-wrap: wrap;
  padding-top: 20px;
}

.my-comment {
  background: #f1e1d1;
  padding: 12px;
  width: 100%;
  margin-top: 20px;

  .input {
    width: calc(100% - 100px);
  }
}
.fun-name {
  color: #ff9d00;
}
.creator {
  color: #ff9d00;
  font-weight: bold;
  font-size: 16px;
}
.comment2 {
  color: #666;
  line-height: 22px;
}
.time {
  font-size: 12px;
  color: #999;
}
.header {
  img {
    width: 30px;
    margin-right: 10px;
    cursor: pointer;
  }
}
.dp-btn {
  display: inline-block;
  line-height: 35px;
  background-color: #ff9d00;
  padding: 0 30px;
  border-radius: 3px;
  color: #fff;
  font-size: 14px;
  text-align: center;
}
.mr10 {
  margin-right: 10px;
}

.price {
  margin-bottom: 10px;
  padding: 15px 20px;
  background-color: #f6f6f6;
  font-size: 12px;
  color: #999;
  margin-bottom: 10px;
}
.old-price {
  color: gray;
  text-decoration: line-through;
  font-size: 14px;
}
.vip-price {
  font-size: 20px;
  color: #ff9d00;
  margin-left: 10px;
  font-weight: bold;
}
.price-font {
  color: #333;
  margin-right: 10px;
  font-size: 14px;
  font-weight: bold;
}
.img-blocks {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  line-height: 60px;
  border: 1px dashed gray;
  text-align: center;
}
.avatar {
  width: 60px;
  height: 60px;
  display: block;
}

.el-icon-circle-close {
  position: absolute;
  top: -5px;
  right: -5px;
  cursor: pointer;
  color: red;
}
::v-deep .el-upload__input {
  display: none;
}
.mb10 {
  margin-bottom: 10px;
}
.mb30 {
  margin-bottom: 30px;
}
.avator{
  width: 40px;
  height: 40px;
  border-radius: 50%;
}
.avator2 {
  background: cyan;
  display: flex;
}

.each-comment {
  width: 100%;
  margin-top: 8px;
  border-bottom: 1px dashed #dedede;
  padding: 0px 0 10px 20px;
  gap: 20px;
  display: flex;
  position: relative;
  .delete {
    position: absolute;
    right: 20px;
    top: 5px;
  }

  .zan {
    position: absolute;
    right: 20px;
    bottom: 5px;
    display: flex;
    flex-wrap: wrap;
    gap: 10px;

    img {
      width: 20px;
      cursor: pointer;
    }
  }

  .picsss {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    img {
      width: 300px;
      height: 200px;
      margin-bottom: 20px;
    }
  }
}
.row {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
  align-items: center;
}
</style>
